<template>
  <div class="profile-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <div class="navbar-left">
          <router-link to="/home" class="logo-link">
            <svg class="logo-icon" viewBox="0 0 48 48" width="36" height="36" fill="none" xmlns="http://www.w3.org/2000/svg">
              <!-- 背景圆角矩形 -->
              <rect width="48" height="48" rx="12" fill="url(#logoGradient)"/>
              <!-- M字母设计 -->
              <path d="M12 32V16L18 24L24 16L30 24L36 16V32" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
              <!-- 小圆点装饰（像数学符号） -->
              <circle cx="18" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <circle cx="30" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <!-- 渐变定义 -->
              <defs>
                <linearGradient id="logoGradient" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
                  <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
                </linearGradient>
              </defs>
            </svg>
            <span class="logo">M-Learning</span>
          </router-link>
        </div>
        <div class="navbar-center">
          <router-link to="/home" class="nav-link">返回首页</router-link>
        </div>
        <div class="navbar-right">
          <div class="user-info">
            <img 
              v-if="userInfo?.avatar" 
              :src="getAvatarUrl(userInfo.avatar)" 
              alt="头像" 
              class="user-avatar-small"
              @click="scrollToTop"
              style="cursor: pointer;"
              title="点击回到顶部修改头像"
            />
            <span 
              v-else 
              class="avatar-placeholder-small"
              @click="scrollToTop"
              style="cursor: pointer;"
              title="点击回到顶部修改头像"
            >
              {{ userInfo?.nickname?.charAt(0) || userInfo?.phone?.charAt(userInfo.phone.length - 1) || '用' }}
            </span>
            <span class="user-name">{{ userInfo?.nickname || userInfo?.phone || '未登录' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="profile-content">
      <div class="profile-container">
        <h1 class="page-title">个人资料</h1>
        
        <div class="profile-card">
          <!-- 头像区域 -->
          <div class="avatar-section">
            <div class="section-label">头像</div>
            <div class="section-content">
              <AvatarUpload 
                :model-value="avatarUrl" 
                :placeholder="userInfo?.nickname?.charAt(0) || userInfo?.phone?.charAt(userInfo.phone.length - 1) || '用'"
                @upload="handleAvatarUpload"
              />
              <div class="avatar-tip">
                <p>支持 JPG、PNG、GIF 格式</p>
                <p>建议尺寸 200x200 像素，大小不超过 5MB</p>
              </div>
            </div>
          </div>

          <!-- 表单区域 -->
          <div class="form-section">
            <!-- 用户名 -->
            <div class="form-item">
              <label class="form-label">
                <span class="label-text">用户名</span>
                <span class="label-required">*</span>
              </label>
              <input 
                v-model="formData.nickname" 
                type="text" 
                class="form-input"
                placeholder="请输入用户名"
                maxlength="20"
              />
              <div class="form-tip">2-20个字符，可包含中文、英文、数字</div>
            </div>

            <!-- 手机号 -->
            <div class="form-item">
              <label class="form-label">
                <span class="label-text">手机号</span>
              </label>
              <input 
                v-model="formData.phone" 
                type="text" 
                class="form-input"
                disabled
              />
              <div class="form-tip">手机号不可修改</div>
            </div>

            <!-- 性别 -->
            <div class="form-item">
              <label class="form-label">
                <span class="label-text">性别</span>
              </label>
              <div class="radio-group">
                <label class="radio-item">
                  <input type="radio" v-model="formData.gender" :value="0" />
                  <span>保密</span>
                </label>
                <label class="radio-item">
                  <input type="radio" v-model="formData.gender" :value="1" />
                  <span>男</span>
                </label>
                <label class="radio-item">
                  <input type="radio" v-model="formData.gender" :value="2" />
                  <span>女</span>
                </label>
              </div>
            </div>

            <!-- 生日 -->
            <div class="form-item">
              <label class="form-label">
                <span class="label-text">生日</span>
              </label>
              <input 
                v-model="formData.birthday" 
                type="date" 
                class="form-input"
              />
            </div>

            <!-- 个人介绍 -->
            <div class="form-item">
              <label class="form-label">
                <span class="label-text">个人介绍</span>
              </label>
              <textarea 
                v-model="formData.bio" 
                class="form-textarea"
                placeholder="介绍一下自己吧~"
                maxlength="200"
                rows="4"
              ></textarea>
              <div class="form-tip">{{ formData.bio?.length || 0 }}/200</div>
            </div>

            <!-- 学校 -->
            <div class="form-item">
              <label class="form-label">
                <span class="label-text">学校</span>
              </label>
              <input 
                v-model="formData.school" 
                type="text" 
                class="form-input"
                placeholder="请输入学校名称"
                maxlength="50"
              />
            </div>

            <!-- 年级 -->
            <div class="form-item">
              <label class="form-label">
                <span class="label-text">年级</span>
              </label>
              <select v-model="formData.grade" class="form-select">
                <option value="">请选择年级</option>
                <option value="小学">小学</option>
                <option value="初中">初中</option>
                <option value="高中">高中</option>
                <option value="大学">大学</option>
                <option value="其他">其他</option>
              </select>
            </div>

            <!-- 按钮 -->
            <div class="form-actions">
              <button class="btn btn-cancel" @click="resetForm">重置</button>
              <button class="btn btn-primary" @click="handleSubmit" :disabled="saving">
                {{ saving ? '保存中...' : '保存修改' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import AvatarUpload from '../components/AvatarUpload.vue'
import { getUserProfile, updateUserProfile, uploadAvatar } from '../api/user'
import { getAvatarUrl } from '../utils/url'

const router = useRouter()
const userStore = useUserStore()
const userInfo = ref(userStore.userInfo)

const formData = reactive({
  avatar: '',
  nickname: '',
  phone: '',
  gender: 0,
  birthday: '',
  bio: '',
  school: '',
  grade: ''
})

const saving = ref(false)

// 计算完整的头像 URL
const avatarUrl = computed(() => getAvatarUrl(formData.avatar))

onMounted(async () => {
  await loadUserProfile()
})

async function loadUserProfile() {
  try {
    const res = await getUserProfile()
    if (res.data) {
      Object.assign(formData, res.data)
      userInfo.value = res.data
      // 更新 store
      userStore.updateUserInfo(res.data)
    }
  } catch (error) {
    console.error('加载用户资料失败:', error)
    // 使用 store 中的数据
    if (userStore.userInfo) {
      Object.assign(formData, userStore.userInfo)
    }
  }
}

async function handleAvatarUpload(formDataObj, callback) {
  try {
    const res = await uploadAvatar(formDataObj)
    if (res.data && res.data.url) {
      // 保存相对路径
      formData.avatar = res.data.url
      // 更新 store（保存相对路径）
      userStore.updateUserInfo({ ...userInfo.value, avatar: res.data.url })
      // 回调函数需要传入完整 URL 用于显示
      callback(getAvatarUrl(res.data.url))
      console.log('头像上传成功:', res.data.url)
      alert('头像上传成功')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    alert(error.message || '头像上传失败，请重试')
  }
}

async function handleSubmit() {
  if (!formData.nickname || formData.nickname.trim().length < 2) {
    alert('请输入至少2个字符的用户名')
    return
  }

  saving.value = true

  try {
    const updateData = {
      nickname: formData.nickname,
      gender: formData.gender,
      birthday: formData.birthday,
      bio: formData.bio,
      school: formData.school,
      grade: formData.grade
    }

    const res = await updateUserProfile(updateData)
    if (res.code === 200) {
      // 更新本地用户信息
      userStore.updateUserInfo({ ...userInfo.value, ...updateData })
      alert('保存成功')
      // 跳转到首页
      router.push('/home')
    }
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

function resetForm() {
  if (confirm('确定要重置所有修改吗？')) {
    loadUserProfile()
  }
}

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}
</script>

<style scoped lang="scss">
.profile-page {
  min-height: 100vh;
  background: #f8f9fa;
}

// 顶部导航栏
.top-navbar {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.navbar-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-left {
  .logo-link {
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 12px;
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      
      .logo-icon {
        transform: rotate(5deg) scale(1.05);
      }
    }
    
    .logo-icon {
      display: block;
      transition: transform 0.3s;
      filter: drop-shadow(0 2px 8px rgba(102, 126, 234, 0.3));
    }
    
    .logo {
      font-size: 24px;
      font-weight: bold;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      letter-spacing: 0.5px;
    }
  }
}

.navbar-center {
  .nav-link {
    color: #333;
    text-decoration: none;
    font-size: 15px;
    transition: color 0.2s;
    
    &:hover {
      color: #667eea;
    }
  }
}

.navbar-right {
  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .user-avatar-small {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      object-fit: cover;
    }
    
    .avatar-placeholder-small {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      font-weight: bold;
    }
    
    .user-name {
      font-size: 14px;
      color: #333;
    }
  }
}

// 主要内容
.profile-content {
  padding: 40px 24px;
}

.profile-container {
  max-width: 800px;
  margin: 0 auto;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
}

.profile-card {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.avatar-section {
  display: flex;
  gap: 24px;
  padding-bottom: 32px;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 32px;
  
  .section-label {
    width: 100px;
    font-size: 14px;
    font-weight: 500;
    color: #666;
    padding-top: 8px;
  }
  
  .section-content {
    flex: 1;
    display: flex;
    align-items: flex-start;
    gap: 24px;
  }
  
  .avatar-tip {
    font-size: 13px;
    color: #999;
    line-height: 1.6;
    
    p {
      margin: 0 0 4px 0;
    }
  }
}

.form-section {
  .form-item {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .form-label {
    display: block;
    margin-bottom: 8px;
    
    .label-text {
      font-size: 14px;
      font-weight: 500;
      color: #333;
    }
    
    .label-required {
      color: #f56c6c;
      margin-left: 4px;
    }
  }
  
  .form-input,
  .form-select,
  .form-textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    font-size: 14px;
    color: #333;
    transition: border-color 0.3s;
    
    &:focus {
      outline: none;
      border-color: #667eea;
    }
    
    &:disabled {
      background: #f5f5f5;
      color: #999;
      cursor: not-allowed;
    }
    
    &::placeholder {
      color: #c0c4cc;
    }
  }
  
  .form-textarea {
    resize: vertical;
    font-family: inherit;
    line-height: 1.6;
  }
  
  .form-tip {
    margin-top: 6px;
    font-size: 12px;
    color: #999;
  }
  
  .radio-group {
    display: flex;
    gap: 24px;
    
    .radio-item {
      display: flex;
      align-items: center;
      gap: 6px;
      cursor: pointer;
      font-size: 14px;
      color: #333;
      
      input[type="radio"] {
        cursor: pointer;
      }
    }
  }
}

.form-actions {
  margin-top: 40px;
  padding-top: 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  padding: 10px 32px;
  border-radius: 6px;
  border: none;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
    
    &:hover {
      background: #e8e8e8;
    }
  }
  
  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    
    &:hover:not(:disabled) {
      opacity: 0.9;
      transform: translateY(-1px);
    }
    
    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }
}
</style>

